package com.axjy.his.service.impl;

import com.axjy.his.controller.vo.Node;
import com.axjy.his.mapper.MenuMapper;
import com.axjy.his.mapper.PermissionMapper;
import com.axjy.his.pojo.Menu;
import com.axjy.his.service.PermissionService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by lenovo on 2017/11/10.
 */
@Service("permissionService")
@Transactional
public class PermissionServiceImpl implements PermissionService {

    @Resource
    private MenuMapper menu;

    @Resource
    private PermissionMapper permissionMapper;

    @Transactional(readOnly = true)
    public List<Node> searchNodes4Tree(Integer roleId) {
        List<Integer> menuList=permissionMapper.searchMenuByRole(roleId);
        List<Node> nodes01=new ArrayList<Node>();
        List<Menu> menus01=menu.searchLevel01();
        for(Menu menu01:menus01){
            Node node01=new Node();
            node01.setIcon(menu01.getIconSkin());
            node01.setId(menu01.getId());
            node01.setText(menu01.getName());
            if(menuList.contains(node01.getId())){
                node01.getState().setChecked(true);
            }
            List<Menu> menus02=menu01.getChildren();
            if(menus02!=null&&menus02.size()>0){
                for(Menu menu02:menus02){
                    Node node02=new Node();
                    node02.setIcon(menu02.getIconSkin());
                    node02.setId(menu02.getId());
                    node02.setText(menu02.getName());
                    node02.setNodes(null);
                    if(menuList.contains(node02.getId())){
                        node02.getState().setChecked(true);
                    }
                    node01.getNodes().add(node02);
                }
            }
            nodes01.add(node01);
        }
        return nodes01;
    }

    public void grant(Integer roleId, Integer[] menuIds) {
        permissionMapper.delete(roleId);
        if(menuIds!=null&&menuIds.length>0){
            for(Integer menuId:menuIds){
                permissionMapper.add(roleId,menuId);
            }
        }
    }

}
